<?php
namespace app\api\controller;


use EasyWeChat\OfficialAccount\Application;
use MoCommon\Support\Codes;;

use think\facade\Log;

class WeChatApi extends Base
{

    public function signature(){
        $config = config('wechat.official_account.default');
        $token = $config["token"]; // 和微信后台一致
        // 获取请求参数
        $signature = input('signature');
        $timestamp = input('timestamp');
        $nonce = input('nonce');
        $echostr = input('echostr');
        // 签名验证
        $tmpArr = [$token, $timestamp, $nonce];
        sort($tmpArr, SORT_STRING); // 字典排序
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        Log::info($signature.'---'.$timestamp.'----'.$nonce.'---'.$echostr);
        Log::info($tmpStr);
        Log::info($token);

        // 如果签名验证通过，返回 echostr，否则返回错误信息
        if ($tmpStr === $signature) {
            echo $echostr; // 微信需要返回这个字符串
        }else{
            echo  'Token verification failed';
        }
        exit;
    }

    public function weChatCallBack()
    {
        $config = config('wechat.official_account.default');
        // 实例化公众号应用
        $app = new Application($config);
        // 获取 OAuth 用户信息
        try {
            $code=input("code");
            $oauth = $app->getOAuth();
            $user = $oauth->userFromCode($code);

            // 用户信息
            $openid = $user->getId(); // 用户 OpenID
            $nickname = $user->getNickname(); // 用户昵称
            $avatar = $user->getAvatar(); // 用户头像
            // 处理登录逻辑，如写入数据库或创建 Session
            echo json_encode([
                'openid' => $openid,
                'nickname' => empty($nickname)?"":$nickname,
                'avatar' => empty($avatar)?"":$avatar,
            ]);
            //测试发送模版消息
            $httpClient = $app->getClient(); // 获取 HTTP 客户端

            $sendData=[
                'touser' => 'oZeFH7A1HxMaXlEdrZMOu1BuPHbA',
                'template_id' => 'jz3MxqvCFgC9Fdf9p7ZsFLJGl5Laooa0_uvTSDMkb-M',
                'url' => 'index',
                'data' => [
                    'teacherName' => ['value' =>'张三'],
                    'dateTime' => ['value' =>'2025-01-08'],
                ],
            ];
            // 发送模板消息
            $response = $httpClient->postJson('/cgi-bin/message/template/send', $sendData);
            $result = $response->toArray();
            var_dump($result);
//            $app->template_message->send($sendData);

        } catch (\Exception $e) {
            echo json_encode(['error' => $e->getMessage()], 500);
        }
        exit;
    }

    public function weChatLogin(){
        $config = config('wechat.official_account.default');
        // 实例化公众号应用
        $app = new Application($config);
        // 跳转到微信授权链接
        $redirectUrl = $app->getOAuth()->redirect();
        Log::info($redirectUrl);
        return redirect($redirectUrl);
    }

}
